<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'

import { computed, ref } from 'vue'
import { Page, useVbenModal } from '@vben/common-ui'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getProcessPurchaseList, deleteProcessPurchase, approvalProcessPurchase, againstProcessPurchase, financialSign, exportContract } from '#/api/backend/processPurchase'
import { Button, message, Popconfirm, Tag, Dropdown, Menu, MenuItem, Input } from 'ant-design-vue'
import { useDebounceFn } from '@vueuse/core'
import dayjs from 'dayjs'

import Form from './modules/form.vue'
import fileManage from '#/adapter/component/FileManage/index.vue'

import { AntPlusOutlined, AntDeleteOutlined, AntCheckOutlined, AntCloseOutlined, AntUploadOutlined } from '@vben/icons'

interface RowType {
  [key: string]: any
}
const params = ref<any>({
  quick_search: '',
})

// 获取选中的行数据
const selectedRows = ref<any>([])

const defaultSort: { field: string; order: '' | 'asc' | 'desc' | null } = {
  field: 'id',
  order: 'desc',
}

const formOptions: VbenFormProps = {
  // fieldMappingTime: [
  //   ['date', ['start', 'end']],
  //   ['create_date', ['create_start', 'create_end']],
  //   ['update_date', ['update_start', 'update_end']],
  //   ['submit_date', ['submit_start', 'submit_end']],
  // ],
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'RangePicker',
      fieldName: 'date',
      label: '单据日期',
      operator: 'RANGE',
      valueToString: true,
      componentProps: {
        allowClear: true,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'Input',
      fieldName: 'sn',
      label: '单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'company_name',
      label: '下单方',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 's*SupplyNa',
      label: '工厂方',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入工厂方',
      },
    },
    {
      component: 'Input',
      fieldName: 'pp*name',
      label: '工序',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'g*goods_no',
      label: '货号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 't*template_no',
      label: '简码',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'isUploadFile',
      label: '是否上传附件',
      operator: 'false',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '是',
            value: 1,
          },
          {
            label: '否',
            value: 0,
          },
        ],
        placeholder: '请选择',
      },
    },
    {
      component: 'Select',
      fieldName: 'state',
      label: '订单状态',
      operator: '=',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '已审核',
            value: 20,
          },
          {
            label: '未审核',
            value: 10,
          },
        ],
        placeholder: '请选择',
      },
    },
    {
      component: 'Select',
      fieldName: 'is_cw_sign',
      label: '财务标记',
      operator: '=',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '已标记',
            value: 1,
          },
          {
            label: '未标记',
            value: 0,
          },
        ],
        placeholder: '请选择',
      },
    },
    {
      component: 'Input',
      fieldName: 'create_name',
      label: '创建人',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'create_date',
      label: '创建时间',
      operator: 'RANGE',
      valueToString: true,
      componentProps: {
        allowClear: true,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'Input',
      fieldName: 'update_name',
      label: '修改人',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'update_date',
      label: '修改时间',
      operator: 'RANGE',
      valueToString: true,
      componentProps: {
        allowClear: true,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'Input',
      fieldName: 'submit_name',
      label: '审核人',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'submit_date',
      label: '审核时间',
      operator: 'RANGE',
      valueToString: true,
      componentProps: {
        allowClear: true,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}
const searchValue:any = ref([])
const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'id',
    isHover: true,
  },
  columnConfig: {
    useKey: true,
  },
  rowStyle({ row }) {
    if (row.state === 10) {
      return {
        color: 'red',
      }
    }
  },
  columns: [
    { type: 'checkbox', width: 70, fixed: 'left' },
    { type: 'seq', title: '序号', width: 50, fixed: 'left' },
    {
      field: 'state',
      width: 80,
      title: '订单状态',
      fixed: 'left',
      slots: { default: 'state' },
    },
    { field: 'sn', width: 130, title: '单号', fixed: 'left' },
    {
      field: 'date',
      width: 100,
      title: '单据日期',
      formatter: ({ cellValue }) => {
        if (cellValue) {
          return dayjs(cellValue).format('YYYY-MM-DD')
        }
        return '-'
      },
    },
    { field: 'company_name', width: 180, title: '下单方' },
    { field: 'SupplyNa', width: 120, title: '工厂方' },
    { field: 'process_name', width: 150, title: '工序' },
    { field: 'goods_no', width: 150, title: '货号' },
    { field: 'template_no', width: 150, title: '简码' },
    { field: 'total_num', width: 100, title: '总数量' },
    {
      field: 'isUploadFile',
      width: 120,
      title: '是否上传附件',
      slots: { default: 'isUploadFile' },
    },
    {
      field: 'is_cw_sign',
      width: 100,
      title: '财务标记',
      slots: { default: 'isCwSign' },
    },
    { field: 'create_name', width: 100, title: '创建人' },
    {
      field: 'create_date',
      width: 160,
      title: '创建时间',
      formatter: ({ cellValue }) => {
        if (cellValue) {
          return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
        }
        return '-'
      },
    },
    { field: 'update_name', width: 100, title: '修改人' },
    {
      field: 'update_date',
      width: 160,
      title: '修改时间',
      formatter: ({ cellValue }) => {
        if (cellValue) {
          return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
        }
        return '-'
      },
    },
    { field: 'submit_name', width: 100, title: '审核人' },
    {
      field: 'submit_date',
      width: 160,
      title: '审核时间',
      formatter: ({ cellValue }) => {
        if (cellValue) {
          return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
        }
        return '-'
      },
    },
    {
      field: 'operation',
      fixed: 'right',
      slots: { default: 'operation' },
      title: '操作',
      width: 150,
    },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    pageSize: 20,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }) => {
        const search = await gridApi.formApi.getFiltersValues()
        searchValue.value = search
        const res = await getProcessPurchaseList({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          quick_search: params.value.quick_search,
          order: sort.field && sort.order ? `${sort.field},${sort.order}` : `${defaultSort.field},${defaultSort.order}`,
        })

        return {
          items: res.list,
          total: res.total,
        }
      },
    },
    sort: true,
  },
  sortConfig: {
    defaultSort,
    remote: true,
  },
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    resizable: true,
    search: true,
    zoom: true,
  },
  id: 'process_purchase_list',
  customConfig: {
    storage: true,
  },
}

// 获取选中行的ID数组
const getSelectionIds = () => {
  return selectedRows.value.map((row: any) => row.id)
}

// 删除按钮判断 - 只有未审核的数据才能删除
const isDisabledDelete = computed(() => {
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.state >= 20)
})

// 审核按钮判断
const isDisabledApproval = computed(() => {
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.state >= 20)
})

// 反审按钮判断
const isDisabledAgainst = computed(() => {
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.state === 10)
})

// 财务标记完结判断
const isDisabledFinancialSignSuccess = computed(() => {
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.is_cw_sign === 1)
})

// 财务反标记判断
const isDisabledFinancialSignError = computed(() => {
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.is_cw_sign === 0)
})

// 处理新建操作
const handleCreate = () => {
  handleFormModal({})
}

// 处理删除操作
const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要删除的数据')
    return
  }
  const hideLoading = message.loading({
    content: '删除',
    duration: 0,
    key: 'action_process_msg',
  })

  deleteProcessPurchase(getSelectionIds())
    .then(() => {
      message.success({
        content: '删除成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理审核操作
const handleApproval = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要审核的数据')
    return
  }
  const hideLoading = message.loading({
    content: '审核',
    duration: 0,
    key: 'action_process_msg',
  })

  approvalProcessPurchase(getSelectionIds())
    .then(() => {
      message.success({
        content: '审核成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理反审操作
const handleAgainst = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要反审的数据')
    return
  }

  const hideLoading = message.loading({
    content: '反审',
    duration: 0,
    key: 'action_process_msg',
  })

  againstProcessPurchase(getSelectionIds())
    .then(() => {
      message.success({
        content: '反审成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理财务标记操作
const handleFinancialSign = (type: 'success' | 'error') => {
  if (selectedRows.value.length === 0) {
    message.warning('请选择要操作的记录')
    return
  }

  const actionText = type === 'success' ? '财务标记完结' : '财务反标记'
  const hideLoading = message.loading({
    content: actionText,
    duration: 0,
    key: 'action_process_msg',
  })

  financialSign(getSelectionIds(), type)
    .then(() => {
      message.success({
        content: `${actionText}成功`,
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理导出合同操作
const handleExportContract = async (menuInfo: any) => {
  const contractType = parseInt(menuInfo.key)

  if (selectedRows.value.length === 0) {
    message.warning('请选择要导出的记录')
    return
  }

  const hide = message.loading('正在导出...', 0)
  try {
    const res = await exportContract(contractType, getSelectionIds())
    console.log(res)
    window.location.href = res.file_url
  } catch (error) {
    message.error('导出失败')
  } finally {
    hide()
  }
}

// 文件管理弹窗配置
const [fileManageModal, fileManageModalApi] = useVbenModal({
  connectedComponent: fileManage,
})

// 打开文件管理与导出
const handleFileManagement = () => {
  const data = gridApi.grid.getCheckboxRecords()
  const ids = data.map((item: any) => item.id)

  fileManageModalApi.setData({ data: ids, type: '5', search: searchValue.value }).open()
}

// 处理表单模态框
const handleFormModal = (row: any) => {
  FormModalApi.setData({
    info: row,
  }).open()
}

const fetchData = async () => {
  gridApi.reload()
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
  },
})

const debouncedReload = useDebounceFn(gridApi.reload, 1000)

const [FormModal, FormModalApi] = useVbenModal({
  connectedComponent: Form,
})
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <Button class="mr-2" type="primary" @click="handleCreate">
          <AntPlusOutlined />
          新建
        </Button>
        <Popconfirm
          title="确认删除"
          :disabled="isDisabledDelete"
          :description="`确定要删除选中的 ${selectedRows.length} 条数据吗？此操作不可恢复。`"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handleDelete"
          @cancel="() => {}"
        >
          <Button class="mr-2" type="primary" danger :disabled="isDisabledDelete">
            <AntDeleteOutlined />
            删除
          </Button>
        </Popconfirm>

        <Popconfirm title="确认审核" :disabled="isDisabledApproval" :description="`确定要审核选中的 ${selectedRows.length} 条数据吗？`" ok-text="确认" cancel-text="取消" @confirm="handleApproval" @cancel="() => {}">
          <Button type="ghost" :class="['mr-2', isDisabledApproval ? 'ant-btn-disabled' : 'bg-[#24b916] text-white hover:opacity-75']" :disabled="isDisabledApproval">
            <AntCheckOutlined />
            审核
          </Button>
        </Popconfirm>
        <Popconfirm title="确认反审" :disabled="isDisabledAgainst" :description="`确定要反审选中的 ${selectedRows.length} 条数据吗？`" ok-text="确认" cancel-text="取消" @confirm="handleAgainst" @cancel="() => {}">
          <Button type="ghost" :class="['mr-2', isDisabledAgainst ? 'ant-btn-disabled' : 'bg-[#f56c6c] text-white hover:opacity-75']" :disabled="isDisabledAgainst">
            <AntCloseOutlined />
            反审
          </Button>
        </Popconfirm>

        <Popconfirm
          v-if="!isDisabledFinancialSignSuccess"
          title="确认财务标记"
          :description="`确定要标记完结选中的 ${selectedRows.length} 条数据吗？`"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handleFinancialSign('success')"
          @cancel="() => {}"
        >
          <Button
            type="ghost"
            class="mr-2 bg-[#24b916] text-white hover:opacity-75"
          >
            财务标记
          </Button>
        </Popconfirm>
        <Popconfirm
          v-if="!isDisabledFinancialSignError"
          title="确认财务反标记"
          :description="`确定要反标记选中的 ${selectedRows.length} 条数据吗？`"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handleFinancialSign('error')"
          @cancel="() => {}"
        >
          <Button
            type="ghost"
            class="mr-2 bg-[#f56c6c] text-white hover:opacity-75"
          >
            财务反标记
          </Button>
        </Popconfirm>

        <Dropdown v-if="selectedRows.length > 0" class="mr-2">
          <Button type="primary">
            导出合同
          </Button>
          <template #overlay>
            <Menu @click="handleExportContract">
              <MenuItem key="1">订单合同</MenuItem>
              <MenuItem key="2">框架合同</MenuItem>
            </Menu>
          </template>
        </Dropdown>

        <Button
          type="ghost"
          class="mr-2 bg-[#cf892d] text-white hover:opacity-75"
          @click="handleFileManagement"
        >
          <AntUploadOutlined />
          附件管理与导出
        </Button>
      </template>
      <template #toolbar-tools>
        <div>
          <Input type="text" placeholder="单号/货号/简码/供应商模糊搜索" v-model:value="params.quick_search" :allow-clear="true" @input="debouncedReload" />
        </div>
      </template>

      <template #isUploadFile="{ row }">
        <Tag :color="row.isUploadFile === 1 ? 'success' : 'error'">
          {{ row.isUploadFile === 1 ? '已上传' : '未上传' }}
        </Tag>
      </template>

      <template #state="{ row }">
        <Tag :color="row.state === 20 ? 'success' : 'error'">
          {{ row.state === 20 ? '已审核' : '未审核' }}
        </Tag>
      </template>

      <template #isCwSign="{ row }">
        <Tag :color="row.is_cw_sign === 1 ? 'success' : 'error'">
          {{ row.is_cw_sign === 1 ? '已标记' : '未标记' }}
        </Tag>
      </template>

      <template #operation="{ row }">
        <Button type="ghost" size="small" @click="handleFormModal(row)">编辑</Button>
      </template>
    </Grid>
    <FormModal @fetch-data="fetchData" />
    <!-- 文件管理弹窗 -->
    <fileManageModal @close="fetchData" />
  </Page>
</template>
